import pymysql
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flask_session import Session

from config import config

# 第三方模块实例化
pymysql.install_as_MySQLdb()
db = SQLAlchemy() # 创建db实例
bootstrap = Bootstrap()
bcrypt = Bcrypt()
login_manager = LoginManager()
mail = Mail()
session = Session()

login_manager.login_view = "auth.login"
login_manager.login_message = "只有登录才可以访问哟 (＾Ｕ＾)ノ~ＹＯ"
login_manager.login_message_category = "info"

def create_app(conf):
    app = Flask(__name__)
    app.config.from_object(config[conf]) # 配置

    # 第三方模块初始化
    db.init_app(app) # 绑定app
    bootstrap.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    session.init_app(app)

    # 创建表，要主动车创建数据库
    from . import models
    db.create_all(app=app)
    
    # 导入蓝图，路由
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint, url_prefix="/")
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix="/auth")
    from .user import user as user_blueprint
    app.register_blueprint(user_blueprint, url_prefix="/user")

    # 钩子函数，服务器的第一个请求将会执行
    app.before_first_request(first_request)
    return app



def first_request():
    from . import models
    # 插入 权限、角色 字段
    models.Permission.insert_permission()
    models.Role.insert_roles()